/****************************************
 * Copyright (c) 2015 NiuWa.
 * All rights reserved.
 * Created on 2015年4月21日
 * 
 * Contributors:
 * 	   Percy.Lo - initial implementation
 ****************************************/
package com.niuwa.p2p.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @title 进度计算工具
 *
 * @author Percy.Lo
 * @version 1.0
 * @created 2015年4月21日
 */
public class ProgressUtils {

	/**
	 * 计算进度
	 * @param current 分子，当前数值
	 * @param total 分母，总数值
	 * @return 如：98.12345%，返回98.12
	 */
	public static BigDecimal calculate(BigDecimal current, BigDecimal total) {
		if (current.compareTo(BigDecimal.ZERO) < 0 || total.compareTo(BigDecimal.ZERO) < 0){
			
			throw new RuntimeException("进度参数值无效,[current:" + current.toPlainString() 
					+ ", total:" + total.toPlainString() + "]");
		}

		BigDecimal p = current.divide(total, 4, RoundingMode.DOWN);
		
		if (p.compareTo(BigDecimal.ONE) > 0 || p.compareTo(BigDecimal.ZERO) < 0){
			
			throw new RuntimeException("进度值不符合范围0~100,[current:" + current.toPlainString() 
					+ ", total:" + total.toPlainString() + "]");
		}
		return p.multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN);
	}

	/**
	 * 计算进度
	 * 
	 * @param addNum 当前投资数值
	 * @param surplusNum 剩余数值
	 * @param total 分母，总数值
	 * @return [进度，新的剩余数值],如：total=100,surplusNum=60,investNum=5 => [65.00,55]
	 */
	public static BigDecimal[] calculate(BigDecimal investNum, BigDecimal surplusNum, BigDecimal total) {
		
		if (investNum.compareTo(BigDecimal.ZERO) < 0 || surplusNum.compareTo(BigDecimal.ZERO) < 0 
				|| total.compareTo(BigDecimal.ZERO) < 0){
			
			throw new RuntimeException("进度参数值无效,[investNum:" + investNum.toPlainString() 
					+ ", total:" + surplusNum.toPlainString() + ", total:" + total.toPlainString() + "]");
		}
		
		BigDecimal current = investNum.add(total.subtract(surplusNum));
		BigDecimal newSurplusNum = surplusNum.subtract(investNum);
		
		return new BigDecimal[] { calculate(current, total), newSurplusNum };
	}
}
